import UIKit

public class JsonUntity
{
    /// <summary>
    /// 将字典类型序列化为json字符串
    /// </summary>
    /// <typeparam name="TKey">字典key</typeparam>
    /// <typeparam name="TValue">字典value</typeparam>
    /// <param name="dict">要序列化的字典数据</param>
    /// <returns>json字符串</returns>
    func getDictionaryFromJSONString(jsonString:String) -> NSDictionary {
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
        
        
    }
    
    /// <summary>
    /// 将json字符串反序列化为字典类型
    /// </summary>
    /// <typeparam name="TKey">字典key</typeparam>
    /// <typeparam name="TValue">字典value</typeparam>
    /// <param name="jsonStr">json字符串</param>
    /// <returns>字典数据</returns>
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try! JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
        
    }
}
